package com.aos.util;

import com.aos.entity.Application;
import com.aos.entity.User;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Date;

/**
 * @ClassName CopyUtils
 * @Description:复制属性值工具
 * @Author wumingwang
 * @Date 2018/9/9 9:48
 * @Version 1.0
 */
public class CopyUtils {

    /**
     * 把source和dest中相同（字段名和类型）的字段的值，并且source不为null的字段，从source复制到dest
     * @param source
     * @param dest
     * @throws Exception
     */
    public static void copy(Object source, Object dest) throws Exception {
        // 获取属性
        BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(),Object.class);
        PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
        BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(),Object.class);
        PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();
        try {
            for (int i = 0; i < sourceProperty.length; i++) {
                for (int j = 0; j < destProperty.length; j++) {
                    if (sourceProperty[i].getReadMethod().invoke(source) != null
                            && sourceProperty[i].getName().equals(destProperty[j].getName())
                            && sourceProperty[i].getPropertyType() == destProperty[j].getPropertyType()) {
                        // 调用source的getter方法和dest的setter方法
                        destProperty[j].getWriteMethod().invoke(dest,sourceProperty[i].getReadMethod().invoke(source));
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception("属性复制失败:" + e.getMessage());
        }
    }
}
